<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.marketingTaskName"
        :placeholder="$t('common.enter', [$t('email.marketingName')])"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
        size="small "
        clearable
      />

      <el-select
        v-model="listQuery.state"
        :placeholder="$t('common.status')"
        clearable
        style="width: 150px"
        class="filter-item"
        size="small"
      >
        <el-option
          v-for="item in stateOptions"
          :key="item.key"
          :label="item.label"
          :value="item.key"
        />
      </el-select>
      <el-select
        v-model="listQuery.sendingType"
        :placeholder="$t('email.method')"
        clearable
        style="width: 150px"
        class="filter-item"
        size="small"
        v-show="this.pageName === 'EmailSendHistory'"
      >
        <el-option
          v-for="item in sendTypeOptions"
          :key="item.key"
          :label="item.label"
          :value="item.key"
        />
      </el-select>
      <el-select
        v-model="listQuery.details"
        :placeholder="$t('email.details')"
        multiple
        collapse-tags
        clearable
        style="width: 180px"
        class="filter-item"
        size="small"
        @change="handleDetailsOptionsChange"
        @remove-tag="handleRemoveDetailsOptionsTag"
        @clear="handleClearDetailsOptionsTag"
      >
        <el-option
          v-for="item in detailsOptionsTemp"
          :key="item.key"
          :label="item.label"
          :value="item.key"
          :disabled="item.disabled"
        />
      </el-select>
      <date-selector
        v-model="listQuery.createdAt"
        type="daterange"
        style="width: 300px; vertical-align: middle"
        value-format="yyyy-MM-dd"
      />
      <div style="display: inline-block; margin-right: 10px"></div>
      <el-button
        plain
        v-waves
        class="filter-item"
        type="primary"
        size="small"
        icon="el-icon-search"
        @click="handleFilter()"
      >
        {{ $t('table.search') }}
      </el-button>
      <el-button
        plain
        class="filter-item"
        type="primary"
        size="small"
        @click="handleExport()"
      >
        导出
      </el-button>
      <el-button
        plain
        size="mini"
        class="filter-item"
        style="margin-left: 10px"
        type="warning"
        icon="el-icon-s-promotion"
        @click="createMarketingTaskByServer"
        v-show="isServerSend"
      >
        {{ $t('route.emailServerSend') }}
      </el-button>
      <el-button
        plain
        class="filter-item"
        style="margin-left: 10px"
        type="success"
        size="mini"
        icon="el-icon-s-promotion"
        @click="handleEmailSendFree"
        v-show="this.pageName === 'EmailSendFree'"
      >
        {{ $t('route.emailSendFree') }}
      </el-button>
      <el-button
        size="small"
        class="filter-item right filter-left filter-refresh"
        icon="el-icon-refresh"
        type="primary"
        plain
        @click="refresh()"
      >
        {{ $t('common.refresh') }}
      </el-button>
      <!-- <el-button
        plain
        v-waves
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        size="small"
        @click=""
      >
        批量删除
      </el-button> -->
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      :height="
        listQuery.total > 0 ? 'calc(100vh - 205px)' : 'calc(100vh - 170px)'
      "
    >
      <el-table-column
        align="center"
        width="50"
        type="index"
        :label="$t('common.id')"
      >
      </el-table-column>
      <el-table-column
        :label="$t('email.customerInfo')"
        align="center"
        min-width="60px"
      >
        <template slot-scope="{ row }">
          <span v-if="row.name">{{ row.name }}</span>
          <span v-else>{{ $t('common.empty') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('customer.customerEmail')"
        align="center"
        min-width="90px"
      >
        <template slot-scope="{ row }">
          {{ row.receiverEmail }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('email.SendType')"
        align="center"
        min-width="40px"
        v-if="this.pageName === 'EmailSendHistory'"
      >
        <template slot-scope="{ row }">
          <template v-for="item in sendTypeOptions">
            <template v-if="item['key'] == row.sendingType">
              <span :key="item['key']" :class="item.class">{{
                item.label
              }}</span>
            </template>
          </template>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('email.senderEmail')"
        align="center"
        min-width="90px"
      >
        <template slot-scope="{ row }">
          {{ row.senderEmail }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('email.sendTime')"
        width="130px"
        align="center"
      >
        <template slot-scope="{ row }">
          <span class="text-xs">{{ row.createdAt }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.status')" width="50px" align="center">
        <template slot-scope="{ row }">
          <template v-for="item in stateOptions">
            <template v-if="item['key'] === row.state">
              <span :class="item.class" v-bind:key="item['key']">{{
                item.label
              }}</span>
            </template>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="已读" width="50px" align="center">
        <template slot-scope="{ row }">
          <span v-if="row.isOpen" class="text-green-500">已读</span>
          <span v-else class="text-gray-400">未读</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="!hideUnsub"
        label="退订"
        width="50px"
        align="center"
      >
        <template slot-scope="{ row }">
          <span v-if="row.isUnsub" class="text-green-500">已退</span>
          <span v-else class="text-gray-400">未退</span>
        </template>
      </el-table-column>
      <el-table-column
        label="邮件标题"
        min-width="150px"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="{ row }">
          <span>{{ row.templateName }}</span>
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('email.marketingTaskSource')"
        align="center"
        width="200px"
      >
        <template slot-scope="{ row }">
          <span
            class="link-type"
            @click="handleShowSendDataTracking(row.source)"
          >
            <el-tag type="info">{{ row.marketingTaskName }}</el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('email.details')"
        align="center"
        width="150px"
      >
        <template slot-scope="{ row }">
          <el-button-group>
            <!-- v-show会导致显示的按钮缺少圆角样式 -->
            <!-- 可以打包到对象数组中循环实现 -->
            <!-- <el-button type="success" size="mini" v-if="row.isOpen" @click="handleDetailsMessage('read',row.messageIDString)">已打开</el-button>
            <el-button type="success" size="mini" v-if="row.isSent" @click="handleDetailsMessage('reply',row.messageIDString)">已回复</el-button>
            <el-button type="success" size="mini" v-if="row.isBounce" @click="handleDetailsMessage('subscribe',row.messageIDString)">被订阅</el-button>
            <el-button type="warning" size="mini" v-if="row.isUnsub" @click="handleDetailsMessage('unsubscribe',row.messageIDString)">被取消订阅</el-button>
            <el-button type="primary" size="mini" v-if="row.isClick" @click="handleDetailsMessage('clickLink',row.messageIDString)">点击链接</el-button>
            <el-button type="danger" size="mini" v-if="row.isSpam" @click="handleDetailsMessage('spam',row.messageIDString)">被标记垃圾邮件</el-button>
            <el-button type="danger" size="mini" v-if="row.isBlocked" @click="handleDetailsMessage('block',row.messageIDString)">被拉黑</el-button> -->
            <template v-for="item in detailsOptionsTemp">
              <el-button
                :type="item.buttonGroupType"
                :key="item.key"
                size="mini"
                v-if="item.buttonGroup && row[item.buttonGroupShow]"
                @click="
                  handleDetailsMessage(item.eventName, row.messageIDString)
                "
              >
                {{ item.label }}
              </el-button>
            </template>
          </el-button-group>
        </template>
      </el-table-column>
      <!--
      <el-table-column
        :label="$t('table.actions')"
        align="center"
        min-width="120"
        class-name="fixed-width"
      >
        <template slot-scope="{row, $index}">
          <el-button
            style="color:#FF7908;border-color:#FF7908;"
            size="mini"
            @click="handleCopy(row)"
          >
            克隆
          </el-button>
          <el-button
            style="color:#FF7908;border-color:#FF7908;"
            size="mini"
            @click="handleDelete(row)"
          >
            标记客户
          </el-button>
          <el-button
            style="color:#FF7908;border-color:#FF7908;"
            size="mini"
            @click="handleDelete(row)"
          >
            添加客户到联系人
          </el-button>
        </template>
      </el-table-column> -->
    </el-table>
    <showSendDataTracking
      :show.sync="showSendDataTrackingVisible"
      :rowId="sendDataTrackingId"
    />
    <pagination
      v-show="listQuery.total > 0"
      :total="listQuery.total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList()"
    />
    <el-dialog
      :title="$t('email.details')"
      :visible.sync="centerDialogVisible"
      width="35%"
      top="100px"
      height="700px"
      center
      @close="handleDetailsDialogClose"
    >
      <div v-if="this.detailsList.length > 0">
        <el-scrollbar
          :wrap-class="{ wrapClass: true }"
          class="dialog-scrollbar"
        >
          <el-collapse
            v-model="activeDeatilsNames"
            @change="handleDetailsTypeChange"
          >
            <template v-for="(item, index) in detailsList">
              <el-collapse-item
                :key="index"
                title="一致性 Consistency"
                :name="index"
              >
                <template slot="title">
                  <el-tag type="info" plain style="font-size: 16px"
                    >时间 ：{{ item.createdAt }}; 事件 ：{{
                      getEventName(item.event)
                    }}</el-tag
                  >
                </template>
                <el-card>
                  <el-form label-width="100px">
                    <el-form-item label="客户邮箱:">
                      <el-tag type="primary" plain style="font-size: 16px">{{
                        item.email
                      }}</el-tag>
                    </el-form-item>
                    <el-form-item label="事件:">
                      <el-tag type="success" plain style="font-size: 16px">{{
                        getEventName(item.event)
                      }}</el-tag>
                    </el-form-item>
                    <el-form-item label="打开时间:">
                      <el-tag type="primary" plain style="font-size: 16px">{{
                        timestampToTime(item.time)
                      }}</el-tag>
                    </el-form-item>
                    <el-form-item label="国家:">
                      <el-tag type="primary" plain style="font-size: 16px">{{
                        getCountry(item.data)
                      }}</el-tag>
                    </el-form-item>
                    <el-form-item label="IP:">
                      <el-tag type="primary" plain style="font-size: 16px">{{
                        getIp(item.data)
                      }}</el-tag>
                    </el-form-item>
                    <el-form-item label="设备/媒介:">
                      <el-tag type="primary" plain style="font-size: 16px">{{
                        getAgent(item.data)
                      }}</el-tag>
                    </el-form-item>
                  </el-form>
                </el-card>
              </el-collapse-item>
            </template>
          </el-collapse>
        </el-scrollbar>
      </div>
      <div v-else>
        <div style="text-align: center; padding-top: 10px">暂无数据</div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleDetailsDialogClose">{{
          $t('common.cancel')
        }}</el-button>
        <el-button type="primary" @click="handleDetailsDialogClose">{{
          $t('permission.confirm')
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination/index.vue'
import { getAction, postAction } from '@/api/common'
import DateSelector from '@/components/Public/dateSelector.vue'
import showSendDataTracking from '../emailMarketingTask/showSendDataTracking.vue'
import { AppModule } from '@/store/modules/app'

export default {
  name: 'EmailSendHistoryIndex',
  components: {
    DateSelector,
    Pagination,
    showSendDataTracking,
  },
  data() {
    const detailsOptions = [
      {
        key: 2,
        label: this.$t('email.sent'),
        icon: 'el-icon-circle-check',
        class: 'notSet',
        disabled: false,
        eventName: 'sent',
        buttonGroup: true,
        buttonGroupType: 'warning',
        buttonGroupShow: 'isSent',
      },
      // {
      //   key: 1,
      //   label: this.$t('email.opened'),
      //   icon: 'el-icon-edit-outline',
      //   class: 'notSet',
      //   disabled: false,
      //   eventName: 'open',
      //   buttonGroup: true,
      //   buttonGroupType: 'success',
      //   buttonGroupShow: 'isOpen',
      // },
      {
        key: -1,
        label: this.$t('email.notOpen'),
        icon: 'el-icon-edit-outline',
        class: 'notSet',
        disabled: false,
        eventName: 'notOpen',
        buttonGroup: false,
        buttonGroupType: 'success',
        buttonGroupShow: 'isOpen',
      }, // 特殊
      {
        key: 4,
        label: this.$t('email.backed'),
        icon: 'el-icon-circle-check',
        class: 'notSet',
        disabled: false,
        eventName: 'bounce',
        buttonGroup: true,
        buttonGroupType: 'warning',
        buttonGroupShow: 'isBounce',
      },
      {
        key: 8,
        label: this.$t('email.unsubscribed'),
        icon: 'el-icon-circle-check',
        class: 'notSet',
        disabled: false,
        eventName: 'unsub',
        buttonGroup: true,
        buttonGroupType: 'success',
        buttonGroupShow: 'isUnsub',
      },
      {
        key: 16,
        label: this.$t('email.linkClicked'),
        icon: 'el-icon-circle-check',
        class: 'notSet',
        disabled: false,
        eventName: 'click',
        buttonGroup: true,
        buttonGroupType: 'primary',
        buttonGroupShow: 'isClick',
      },
      {
        key: 32,
        label: this.$t('email.markedAsJunk'),
        icon: 'el-icon-circle-check',
        class: 'notSet',
        disabled: false,
        eventName: 'spam',
        buttonGroup: true,
        buttonGroupType: 'danger',
        buttonGroupShow: 'isSpam',
      },
      {
        key: 64,
        label: this.$t('email.blacklist'),
        icon: 'el-icon-circle-check',
        class: 'notSet',
        disabled: false,
        eventName: 'blocked ',
        buttonGroup: true,
        buttonGroupType: 'danger',
        buttonGroupShow: 'isBlocked',
      },
    ]
    return {
      list: [],
      listLoading: false,
      centerDialogVisible: false,
      detailsList: [],
      activeDeatilsNames: [0],
      listQuery: {
        page: 1,
        limit: 20,
        total: 0,
        marketingTaskName: undefined,
        type: undefined,
        sendingType: undefined,
        createdAt: undefined,
        details: undefined,
        pageName: '',
      },
      detailsOptionOldValue: [],
      showSendDataTrackingVisible: false,
      sendDataTrackingId: 0,
      stateOptions: [
        {
          key: true,
          label: this.$t('common.success'),
          icon: 'el-icon-edit-outline',
          class: 'state_unsubmit',
        },
        {
          key: false,
          label: this.$t('email.failed'),
          icon: 'el-icon-circle-check',
          class: 'state_submit',
        },
      ],
      sendTypeOptions: [
        {
          key: '1',
          label: this.$t('route.emailSendFree'),
          icon: 'el-icon-edit-outline',
          class: 'state_unsubmit',
        },
        {
          key: '2',
          label: this.$t('route.emailServerSend'),
          icon: 'el-icon-circle-check',
          class: 'state_submit',
        },
      ],
      detailsOptions,
      detailsOptionsTemp: JSON.parse(JSON.stringify(detailsOptions)),
    }
  },
  created() {
    this.getList()
  },
  computed: {
    pageName() {
      const path = this.$route.path
      if (path.includes('emailSendHistory')) {
        return 'EmailSendHistory'
      } else if (path.includes('emailSendFree')) {
        return 'EmailSendFree'
      } else if (path.includes('emailServerSend')) {
        return 'EmailServerSend'
      } else if (path.includes('emailRushEmailSend')) {
        return 'EmailRushEmailSend'
      }
      return undefined
    },
    isServerSend() {
      return (
        this.pageName === 'EmailServerSend' ||
        this.pageName === 'EmailRushEmailSend'
      )
    },
    hideUnsub() {
      return AppModule.ui.hideUnsub
    },
  },
  methods: {
    refresh() {
      this.listQuery = {
        page: 1,
        limit: 20,
        total: 0,
        marketingTaskName: undefined,
        type: undefined,
        sendingType: undefined,
        createdAt: undefined,
        details: undefined,
        pageName: this.pageName,
      }
      this.getList()
    },
    getEventName(val) {
      for (const item in this.detailsOptions) {
        console.log(item)
        if (this.detailsOptions[item].eventName === val) {
          return this.detailsOptions[item].label
        }
      }
    },
    getList() {
      this.listLoading = true
      this.listQuery.pageName = this.pageName
      postAction(this.listQuery, 'EmailSendHistory/index').then(({ data }) => {
        this.list = data.items
        this.listQuery.total = data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleDetailsOptionsChange(val) {
      console.log(val)
      this.getDetailsOptionsDisabledValue(val)
    },
    getDetailsOptionsDisabledValue(val) {
      this.detailsOptionsTemp = this.detailsOptionsTemp.map((m) => ({
        ...m,
        disabled: val.indexOf(-m.key) !== -1,
      }))
    },
    handleRemoveDetailsOptionsTag(val) {
      // 上方input框每个选项的小叉叉触发
      this.detailsOptionsTemp = this.detailsOptionsTemp.map((m) => {
        if (m.key === -val) {
          m.disabled = false
        }
        return m
      })
    },
    handleClearDetailsOptionsTag() {
      // 上方input框后的小叉叉触发
      // 重置值
      console.log('clear')
      this.detailsOptionsTemp = JSON.parse(JSON.stringify(this.detailsOptions))
    },
    handleShowSendDataTracking(value) {
      this.showSendDataTrackingVisible = true
      console.log('value', value)
      this.sendDataTrackingId = value
    },
    handleEmailSendFree() {
      this.$router.push('/email/emailSendFree/add?fromPage=Index')
    },
    createMarketingTaskByServer() {
      let uri = '/email/emailServerSend/add?fromPage=Index'
      if (this.pageName === 'EmailRushEmailSend') {
        uri += '&server=rushemail'
      }
      this.$router.push(uri)
    },
    handleDetailsMessage(eventType, messageId) {
      this.centerDialogVisible = true
      console.log(eventType)
      getAction(
        { messageId, eventType },
        'EmailSendHistory/GetDetailsByMessageId'
      )
        .then((res) => {
          this.detailsList = res.data
          console.log(res)
        })
        .finally(() => {
          console.log('获取邮件详情结束')
        })
    },
    handleDetailsTypeChange(val) {
      console.log(val)
    },
    handleDetailsDialogClose() {
      this.centerDialogVisible = false
      this.detailsList = []
    },
    getCountry(val) {
      const jsonData = JSON.parse(val)
      return jsonData.geo ?? this.$t('common.empty')
    },
    getIp(val) {
      const jsonData = JSON.parse(val)
      return jsonData.ip ?? this.$t('common.empty')
    },
    getAgent(val) {
      const jsonData = JSON.parse(val)
      return jsonData.agent ?? this.$t('common.empty')
    },
    timestampToTime(timestamp) {
      const date = new Date((timestamp - 8 * 3600) * 1000)
      const Y = date.getFullYear() + '-'
      const M =
        (date.getMonth() + 1 < 10
          ? '0' + (date.getMonth() + 1)
          : date.getMonth() + 1) + '-'
      const D =
        (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
      const h =
        (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
      const m =
        (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) +
        ':'
      const s =
        date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      return Y + M + D + h + m + s
    },
    getShowResult(row, name) {
      return row[name] === true
    },
    handleExport() {
      const a = document.createElement('a')
      a.href = '/api/emailSendHistory/download?ids=&all=true'
      a.click()
    },
  },
}
</script>

<style scoped>
.state_unsubmit {
  color: #609cd3;
}

.state_unsubmit > i {
  font-size: 20px;
  margin-right: 5px;
}

.state_submit {
  color: plum;
}

.state_submit > i {
  font-size: 20px;
  margin-right: 5px;
}

.state_cancel {
  color: orange;
}

.state_cancel > i {
  font-size: 20px;
  margin-right: 5px;
}

.state_complete {
  color: green;
}

.state_complete > i {
  font-size: 20px;
  margin-right: 5px;
}

.count_icon > i {
  color: #ff7908;
  font-size: 20px;
  margin-right: 5px;
}

.dialog-scrollbar {
  height: 620px;
}
</style>
